package com.saer.client.tab;

import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.tab.Tab;

public abstract class BaseTab extends Tab {

	private int tabType = -1;
	private int activeCallbacks = 0;
	protected String tabTitle = "";
	private String tabTitleSuffix = "";
	private String callbackName = "";
	
	public BaseTab() {
		super();
	}
	
	public BaseTab(int tabType) {
		this();
		this.tabType = tabType;
	}

	public void setTabTitleSuffix(String tabTitleSuffix) {
		this.tabTitleSuffix = tabTitleSuffix;
	}

	public void showWorkingWidget() {
		activeCallbacks++;
		super.setTitle("" + Canvas.imgHTML("animations/working.gif") + " " + tabTitle + tabTitleSuffix);
	}
	
	public void showErrorIcon(String errorMessage, String callbackName) {
		hideWorkingWidget();
		this.callbackName = formatMethodName(callbackName);
		super.setTitle("" + Canvas.imgHTML("icons/16/warning.png") + " " + tabTitle + tabTitleSuffix);
		getTabCanvas().setShowHover(true);
		getTabCanvas().setTooltip(errorMessage);
		SC.warn("<b>While executing " + this.callbackName + ":</b><br> " + errorMessage);
	}
	
	public void removeWarningIcon() {
		super.setTitle(tabTitle + tabTitleSuffix);
		getTabCanvas().setShowHover(false);
	}
	
	public void showWarningIcon(String warningMessage) {
		super.setTitle("" + Canvas.imgHTML("icons/16/exclamation_red.png") + " " + tabTitle + tabTitleSuffix);
		getTabCanvas().setShowHover(true);
		getTabCanvas().setTooltip(warningMessage);
	}

	private String formatMethodName(String callbackName) {
		String methodName = callbackName.substring(callbackName.indexOf('$') + 1).split("CallBack")[0];
		
		char[] chars = methodName.toCharArray();
		char[] methodNameWithSpaces = new char[chars.length+7];
		
		for (int i = 0, j = 0; i < chars.length; i++, j++) {
			if (Character.isUpperCase(chars[i]) && i != 0) {
				methodNameWithSpaces[j++] = ' ';
			}
			methodNameWithSpaces[j] = chars[i];
		}
		
		return new String(methodNameWithSpaces);
	}
	
	public void hideWorkingWidget() {
		activeCallbacks--;
		if (activeCallbacks == 0) {
			super.setTitle(tabTitle + tabTitleSuffix);
		}
	}

	public int getTabType() {
		return tabType;
	}
	
	@Override
	public void setTitle(String title) {
		this.tabTitle = title;
		super.setTitle(title);
	}

}
